package com.goal98.team.controllers

import grails.converters.JSON
import grails.converters.XML
import com.goal98.team.domain.Team
import com.goal98.team.ResourceNotFoundException

class MyteamController {

    def authenticateService
    def myteamService
    def notificationService

    def index = { redirect(action: show, params: params) }

    // the delete, save and update actions only accept POST requests
    //static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def edit = {

        def teamInstance = myteamService.getMyteam()

        if (!teamInstance) {
            flash.message = message(code: 'myteam.noteam', 'default': "You don't belong to any TEAM!")
            redirect(action: list)
        }
        else {
            return [teamInstance: teamInstance]
        }
    }

    /**
     * rest actions
     */

    def show = {
        def teamInstance = myteamService.getMyteam()
        if (!teamInstance) {
            final notFoundMessage = message(code: 'myteam.noteam', 'default': "You don't belong to any TEAM!")
            withFormat {
                html {

                    flash.message = notFoundMessage
                    redirect(action: apply)
                }
                xml {
                    response.status = 404
                    render(view: "/errorxml",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(notFoundMessage)])
                }
                json {
                    response.status = 404
                    render(view: "/errorjson",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(notFoundMessage)])
                }
            }

        }
        else {
            withFormat {
                html {
                    return [teamInstance: teamInstance]
                }
                xml {
                    render teamInstance as XML
                }
                json {
                    render teamInstance as JSON
                }
            }

        }

    }


    def update = {
        def teamInstance = myteamService.getMyteam()
        if (teamInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (teamInstance.version > version) {
                    withFormat {
                        form {

                            teamInstance.errors.rejectValue("version", "team.optimistic.locking.failure", "Another user has updated this Team while you were editing.")
                            render(view: 'edit', model: [teamInstance: teamInstance])
                        }

                        xml {
                            response.status = 500
                            render teamInstance.errors as XML
                        }
                        json {
                            response.status = 500
                            render teamInstance.errors as JSON
                        }

                    }

                }
            }
            teamInstance.properties = params
            if (!teamInstance.hasErrors() && teamInstance.save()) {
                final String updateSuccessMsg = "Team ${params.id} updated"
                withFormat {
                    form {
                        flash.message = updateSuccessMsg
                        redirect(action: show, id: teamInstance.id)
                    }
                    xml {
                        render teamInstance as XML
                    }
                    json {
                        render teamInstance as JSON
                    }
                }


            }
            else {
                withFormat {
                    form {
                        render(view: 'edit', model: [teamInstance: teamInstance])
                    }
                    xml {
                        response.status = 500
                        render teamInstance.errors as XML
                    }
                    json {
                        response.status = 500
                        render teamInstance.errors as JSON
                    }
                }

            }
        }
        else {
            final String updateNotFoundMsg = message(code: 'myteam.noteam', 'default': "You don't belong to any TEAM!")
            withFormat {
                form {
                    flash.message = updateNotFoundMsg
                    redirect(action: edit, id: params.id)
                }
                xml {
                    response.status = 404
                    render(view: "/errorxml",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(updateNotFoundMsg)])
                }
                json {
                    response.status = 404
                    render(view: "/errorjson",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(updateNotFoundMsg)])
                }
            }

        }
    }

    def apply = {

    }

    def doSearch = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def query = params.query
        def teamInstanceList = Team.findAllByNameLike("%$query%", params)
        def total = Team.countByNameLike("%$query%")
        render(view:'apply', model:[teamInstanceList:teamInstanceList, total:total])
    }

    def doApply = {

    }

    def account = {
        def team = myteamService.getMyteam()

        if(!team){
            flash.message = message(code:'myteam.noteam', 'default':'You do not have a team yet')
            redirect(controller:"info",action:"teamCloud")
        }

        if(team && team.account == null){
            myteamService.openAccount(team)
        }
        def view = session.mobile?'m-account':'account'
        render (view:view,model:[teamInstance:team])
    }

    def notifyUpcomingActivity = {
        def team = myteamService.getMyteam()
        notificationService.sendUpcomingActivityNotification(team)
        render "Done!"
    }
}